using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Deepcode.Flux.Core.Services.FluxClient;

namespace Deepcode.Flux.Core.UI.Controls
{
	public enum DateInputType{ NORMAL, WITHTIME };
	/// <summary>
	/// DateInput provides a standard text input control, but
	/// with a date selection moniker which will popup a date
	/// selection browser.
	/// </summary>
	public class DateInput : Base.BaseTextBoxControl
	{
		#region Properties
		/// <summary>
		/// Returns the value of the input as a System.DateTime object
		/// </summary>
		public System.DateTime DateTimeValue
		{
			get
			{
				try
				{
					System.DateTime dt = System.DateTime.Parse(this.Text);
					return dt;
				}
				catch
				{
					return System.DateTime.Now;
				}
			}
		}
		/// <summary>
		/// Determines the type of the input - IE: Normal or with a time selector
		/// </summary>
		public DateInputType Type
		{
			get
			{
				object o = ViewState["type"];
				if( o == null ) return DateInputType.NORMAL;
				return (DateInputType) o;
			}
			set
			{
				ViewState["type"] = value;
			}
		}
		#endregion
		#region Rendering
		/// <summary>
		/// Default rendering
		/// </summary>
		/// <param name="writer"></param>
		protected override void Render(HtmlTextWriter writer)
		{
			base.Render (writer);

			string typeCode = "CAL_JUSTDATE";
			if( Type == DateInputType.WITHTIME ) typeCode = "CAL_WITHTIME";
			writer.Write(" <img src='{0}' width='16' height='15' style='cursor:pointer;' onclick='__PopupCalendar(this, \"{1}\", {2});'>",
				ClientHelper.GetFluxClientFile("DateInput/Calendar.gif"),
				this.ClientID,
				typeCode);
		}
		#endregion
		
		/// <summary>
		/// Pre-Render phase - register scripts etc
		/// </summary>
		/// <param name="e"></param>
		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender (e);
			// Register the script block
			this.LoadClientScript("DateInput/DateInput.js", "Deepcode.Flux.Core.UI.Controls.DateInputJS");

			// Register the hidden popup div, using the template associated as a resource of this assembly
			/* Read in the entire template from the resource */
			System.Reflection.Assembly exe = System.Reflection.Assembly.GetExecutingAssembly();
			System.IO.Stream input = exe.GetManifestResourceStream("Deepcode.Flux.Core.UI.Controls.DateTime.HTObject.htf.htm");
			if( input == null ) throw new Exception("Error reading template resource - OnPreRender DateInput");
		
			System.IO.StreamReader r = new System.IO.StreamReader(input);
			string template = r.ReadToEnd();
			r.Close();
			input.Close();

			/* Add it as a script block */
			Page.ClientScript.RegisterClientScriptBlock(
				this.GetType(),
				"Deepcode.Flux.Core.UI.Controls.DateInput.DIV",
				template);
		}
	}
}
